package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepositoey;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepositoey travelCommentRepositoey;
    @Autowired
    private MongoTemplate template;
    private Pageable pageable;

    @Override
    public List<TravelComment> list() {
        return travelCommentRepositoey.findAll();
    }

    @Override
    public TravelComment selectOne(String id) {
        return travelCommentRepositoey.findById(id).orElse(null);
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        //创建查询对象
        Query query = new Query();
        //页面显示集合
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");
        return DBHelper.query(template, TravelComment.class, query, pageable);

    }

    @Override
    public void save(TravelComment travelComment) {
        travelCommentRepositoey.save(travelComment);
    }

    @Override
    public void delete(String id) {
        travelCommentRepositoey.deleteById(id);
    }


    @Override
    public List<TravelComment> selectByTId(String travelId) {
        if(StringUtils.hasLength(travelId)){
            List<TravelComment> travels = travelCommentRepositoey.findByTravelId(travelId);
            return travels;
        }
        return null;
    }

    @Override
    public void commentAdd(TravelComment comment) {
        //设置创建评论时间
        comment.setCreateTime(new Date());
        //添加前将id设置为null
        comment.setId(null);
        //维护运用评论对象
        String id = comment.getRefComment().getId();
        if (StringUtils.hasLength(id)){
            //有的话,就是评论的评论
            TravelComment travelComment = this.selectOne(id);
            //设置进原先的评论中
            comment.setRefComment(travelComment);
            //还要改变其状态
            comment.setType(TravelComment.TRAVLE_COMMENT_TYPE);
        }
        this.save(comment);
    }


}

